package leetcode;

import com.alibaba.druid.sql.visitor.functions.Char;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: DRevelation
 * @Date: 2020/12/23 13:36
 * 给定一个字符串，找到它的第一个不重复的字符，并返回它的索引。如果不存在，则返回 -1。
 * <p>
 * <p>
 * <p>
 * 示例：
 * <p>
 * s = "leetcode"
 * 返回 0
 * <p>
 * s = "loveleetcode"
 * 返回 2
 * <p>
 * <p>
 * <p>
 * 提示：你可以假定该字符串只包含小写字母。
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/first-unique-character-in-a-string
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Case387 {
    public static void main(String[] args) {
        System.out.println(firstUniqChar("leetcode"));
        System.out.println(firstUniqChar("loveleetcode"));
        System.out.println("============================");
        System.out.println(firstUniqChar2("leetcode"));
        System.out.println(firstUniqChar2("loveleetcode"));
        System.out.println("============================");
        System.out.println(firstUniqChar3("leetcode"));
        System.out.println(firstUniqChar3("loveleetcode"));
    }

    private static int firstUniqChar(String s) {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (s.indexOf(c) == s.lastIndexOf(c)) {
                return i;
            }
        }
        return -1;
    }

    private static int firstUniqChar2(String s) {
        int[] arr = new int[26];
        int length = s.length();
        for (int i = 0; i < length; i++) {
            arr[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < length; i++) {
            if (arr[s.charAt(i) - 'a']++ == 1) {
                return i;
            }
        }
        return -1;
    }

    private static int firstUniqChar3(String s) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for (int i = 0; i < s.length(); i++) {
            if (map.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }
}
